package com.jdls.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.jdls.tanhua.dubbo.CommentApi;
import com.jdls.tanhua.dubbo.UserInfoApi;
import com.jdls.tanhua.dubbo.VideoApi;
import com.jdls.tanhua.enums.CommentType;
import com.jdls.tanhua.exception.AllException;
import com.jdls.tanhua.interceptor.UserHolder;
import com.jdls.tanhua.mongo.Comment;
import com.jdls.tanhua.mongo.Video;
import com.jdls.tanhua.pojo.UserInfo;
import com.jdls.tanhua.template.OssTemplate;
import com.jdls.tanhua.vo.ErrorResult;
import com.jdls.tanhua.vo.PageResult;
import com.jdls.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 嘉德罗斯
 * @date 2021/11/6
 */
@Service
public class VideoServer {

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL



    public void smallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        ///1、封面图上传到阿里云OSS，获取地址
        String picUrl = ossTemplate.oss(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //视频上传
        //获取文件的后缀名
        String filename = videoFile.getOriginalFilename();  //ssss.avi
        String sufix = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), sufix, null);
        //获取视频地址
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //设置保存的数据
        Video video = new Video();
        video.setVideoUrl(videoUrl);
        video.setPicUrl(picUrl);
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());

        videoApi.save(video);
    }

    //查看视频列表
    public PageResult find(Integer page, Integer pagesize) {
        List<Video> videos = videoApi.findAll(page,pagesize);
        //获取视频列表的id集合
        List<Long> ids = CollUtil.getFieldValues(videos, "userId", Long.class);
        //根据id集合查询用户资料
        List<UserInfo> userInfos = userInfoApi.findAll(ids);

        List<VideoVo> videoVos = new ArrayList<>();
        for (Video video : videos) {
            for (UserInfo userInfo : userInfos) {
                if (video.getUserId() == userInfo.getId()){
                    VideoVo init = VideoVo.init(userInfo, video);
                    videoVos.add(init);
                }
            }
        }

        PageResult pageResult = new PageResult(page,pagesize,videoVos.size(),videoVos);
        return pageResult;
    }

    //视频点赞
    public Integer like(ObjectId id) {
        //当前用户id
        Long userId = UserHolder.getUserId();
        //互动类型
        int like = CommentType.LIKE.getType();

        //判断当前用户是否点赞
        Comment comment = commentApi.find(userId,id,like);
        if(comment != null){
            throw new AllException(ErrorResult.likeErr());
        }
        //未点赞则保存一条数据
        comment = new Comment();
        comment.setPublishId(id);
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = commentApi.save(comment);

        //主key
        String key =  id+"";
        //hashKey
        String hashKey = CommentType.LIKE.getType()+"_"+userId;

        redisTemplate.opsForHash().put(key,hashKey,"1");

        return likeCount;
    }

    //视频取消点赞
    public Integer dislike(ObjectId id) {
        //当前用户id
        Long userId = UserHolder.getUserId();
        //互动类型
        int like = CommentType.LIKE.getType();
        //判断当前用户是否点赞
        Comment comment = commentApi.find(userId,id,like);
        if(comment == null){
            //如果不存在就是未点赞
            throw new AllException(ErrorResult.dislikeErr());
        }
        //目前最新的数据
        Integer count = commentApi.delete(userId, id, like);

        //主key
        String key =  id+"";
        //hashKey
        String hashKey = CommentType.LIKE.getType()+"_"+userId;

        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
